package com.liukai.bishe.presenter.userPresenter.impl;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.liukai.bishe.BuildConfig;
import com.liukai.bishe.presenter.userPresenter.IUpdateHeadImgPresenter;
import com.liukai.bishe.utils.Constants;
import com.liukai.bishe.utils.FileUtils;
import com.liukai.bishe.view.IBaseCallBack;
import com.liukai.bishe.view.IUpdateHeadImgCallBack;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 * 处理更新头像的数据
 */
public class IUpdateHeadImgPresenterImpl implements IUpdateHeadImgPresenter {

    private File mTmpFile;
    private File mCropImageFile;

    private Activity mActivity;
    private IUpdateHeadImgCallBack mIUpdateHeadImgCallBack;

    public IUpdateHeadImgPresenterImpl(Activity activity){
        mActivity = activity;
    }


    @Override
    public void registerCallback(IBaseCallBack iBaseCallBack) {
        mIUpdateHeadImgCallBack = (IUpdateHeadImgCallBack)iBaseCallBack;
    }

    @Override
    public void unregisterCallback(IBaseCallBack iBaseCallBack) {
        if (mIUpdateHeadImgCallBack != null) {
            mIUpdateHeadImgCallBack = null;
        }

    }

    /**
     * 打开相册
     */
    @Override
    public void gallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        mActivity.startActivityForResult(intent, Constants.REQUEST_GALLERY);
    }

    /**
     * 打开相机
     */
    @Override
    public void camera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(mActivity.getPackageManager()) != null) {
            mTmpFile = new File(FileUtils.createRootPath(mActivity.getBaseContext()) + "/" + System.currentTimeMillis() + ".jpg");
            FileUtils.createFile(mTmpFile);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        FileProvider.getUriForFile(mActivity.getBaseContext(), BuildConfig.APPLICATION_ID + ".provider", mTmpFile));
            }else {
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            }
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            mActivity.startActivityForResult(cameraIntent, Constants.REQUEST_CAMERA);
        }
    }

    /**
     * 把fileUri转换成ContentUri
     * @param imageFile
     * @return
     */
    @Override
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = mActivity.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return mActivity.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     *获取裁剪的图片保存地址
     * @return
     */
    @Override
    public File getmCropImageFile() {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),"temp.jpg");
            File file = new File(mActivity.getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
//            mIUpdateHeadImgCallBack.result(file);
            return file;
        }
        return null;
    }

    /**
     *获取地址
     * @param data
     * @return
     */
    @Override
    public String handleImage(Intent data) {
        Uri uri = data.getData();
        String imagePath = null;
        if (Build.VERSION.SDK_INT >= 19) {
            if (DocumentsContract.isDocumentUri(mActivity, uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("" +
                            "content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equals(uri.getScheme())) {
                imagePath = getImagePath(uri, null);
            }
        } else {
            imagePath = getImagePath(uri, null);
        }
        return imagePath;
    }

    /**
     * 获取图片地址
     * @param uri
     * @param seletion
     * @return
     */
    @Override
    public String getImagePath(Uri uri, String seletion) {
        String path = null;
        Cursor cursor = mActivity.getContentResolver().query(uri, null, seletion, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    @Override
    public File getTmpFile() {
        return this.mTmpFile;
    }


}
